const express = require('express');
const router = express.Router();
const db = require('../config/db');
const { validatePost } = require('../middleware/validator');

// 获取帖子列表（添加分类信息）
router.get('/posts', (req, res) => {
  db.query(`
    SELECT p.*, u.username, c.name as category_name,
           (SELECT COUNT(*) FROM likes WHERE post_id = p.id) as like_count
    FROM posts p
    JOIN users u ON p.user_id = u.id
    LEFT JOIN categories c ON p.category_id = c.id
    ORDER BY p.created_at DESC
  `, (error, results) => {
    if (error) {
      return res.status(500).json({ error: error.message });
    }
    res.json(results);
  });
});

// 创建帖子（添加分类）
router.post('/posts', validatePost, (req, res) => {
  const { title, content, category_id } = req.body;
  const user_id = req.user.id;

  db.query(
    'INSERT INTO posts (user_id, title, content, category_id) VALUES (?, ?, ?, ?)',
    [user_id, title, content, category_id],
    (error, results) => {
      if (error) {
        return res.status(500).json({ error: error.message });
      }
      res.json({ 
        id: results.insertId, 
        message: '帖子创建成功' 
      });
    }
  );
});

module.exports = router; 